package edu.whu.xterm.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import edu.whu.xterm.R;

public class MailboxFragment extends Fragment implements OnTabChangeListener {

	public static final String INBOX = "inbox";
	public static final String OUTBOX = "outbox";

	private View root;
	private TabHost tabHost;
	private LayoutInflater mInflater;
	private int currentTab;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mInflater = inflater;
		root = inflater.inflate(R.layout.fragment_mailbox, null);
		tabHost = (TabHost) root.findViewById(android.R.id.tabhost);
		tabHost.setup();
		tabHost.addTab(newTab(INBOX, R.string.inbox, R.id.tab_inbox));
		tabHost.addTab(newTab(OUTBOX, R.string.outbox, R.id.tab_outbox));
		return root;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setRetainInstance(true);
		tabHost.setOnTabChangedListener(this);
		tabHost.setCurrentTab(1);
		//updateTab(INBOX, R.id.tab_inbox);
	}

	private TabSpec newTab(String tab, int labelId, int contentId) {
		View indicator = mInflater.inflate(R.layout.tab_mailbox,
				(ViewGroup) root.findViewById(android.R.id.tabs), false);
		((TextView) indicator.findViewById(R.id.text)).setText(labelId);
		TabSpec spec = tabHost.newTabSpec(tab);
		spec.setIndicator(indicator);
		spec.setContent(contentId);
		return spec;
	}

	@Override
	public void onTabChanged(String tabId) {
		if (INBOX.equals(tabId)) {
			updateTab(tabId, R.id.tab_inbox);
		}

	}

	private void updateTab(String tabId, int place) {
		FragmentManager fm = getFragmentManager();
		if (fm.findFragmentByTag(tabId) == null) {
			fm.beginTransaction().replace(place, getTargetFragment(), tabId).commit();
		}
	}

}
